#!/bin/bash
# build a project

set -e

PRODUCT="A9"
BUILD_TMP_DIR=build_arm_tmp
BUILD_TYPE=RelWithDebInfo

function build_A9_project() {
    echo -e "\033[32m===>build A9 project: $1\033[0m"
    echo "build $BUILD_TYPE ..."
    cd ~/repos/$1
    if [ ! -d ${BUILD_TMP_DIR}_A9 ]; then
        mkdir ${BUILD_TMP_DIR}_A9
    fi
    cd ${BUILD_TMP_DIR}_A9
    cmake -DCMAKE_TOOLCHAIN_FILE=/opt/crossplatform/arm49/env.cmake -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DMULTI_BOARD_POWER_QUALITY=ON ..
    make -j4
    make install
    echo "build ok!"
}

function build_A7_project() {
    echo -e "\033[32m===>build A7 project: $1\033[0m"
    echo "build $BUILD_TYPE ..."
    cd ~/repos/$1
    if [ ! -d ${BUILD_TMP_DIR}_A7 ]; then
        mkdir ${BUILD_TMP_DIR}_A7
    fi
    cd ${BUILD_TMP_DIR}_A7
    cmake -DCMAKE_TOOLCHAIN_FILE=/opt/crossplatform/arm49/env.cmake -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DSINGLE_BOARD_POWER_QUALITY=ON ..
    make -j4
    make install
    echo "build ok!"
}

function build_project() {
    echo -e "\033[32m===>build project: $1\033[0m"
    echo "build $BUILD_TYPE ..."
    cd ~/repos/$1
    if [ ! -d ${BUILD_TMP_DIR} ]; then
        mkdir ${BUILD_TMP_DIR}
    fi
    cd ${BUILD_TMP_DIR}
    cmake -DCMAKE_TOOLCHAIN_FILE=/opt/crossplatform/arm49/env.cmake -DCMAKE_BUILD_TYPE=${BUILD_TYPE} ..
    make -j4
    make install
    echo "build ok!"
}

if [ $# -ge 2 ]; then
    if [[ "$2" != "Release" && "$2" != "Debug" && "$2" != "RelWithDebInfo" ]]; then
        echo "usage: $0 <A7|A9> <Release|Debug|RelWithDebInfo> <project name> "
        exit -1
    fi

    BUILD_TYPE="$2"
fi

if [ $# -ge 1 ]; then
    if [[ "$1" != "A9" && "$1" != "A7" ]]; then
        echo "usage: $0 <A7|A9> <Release|Debug|RelWithDebInfo> <project name> "
        exit -1
    fi

    PRODUCT="$1"
fi

if [ $# -ge 3 ]; then
    if [ $3 = "WzSCTP" ] || [ $3 = "WzComtrade" ] || [ $3 = "WzTransient" ] ||
        [ $3 = "WzWaveSimulate" ] || [ $3 = "WzModbus" ] || [ $3 = "WzPQDIF" ] ||
        [ $3 = "WzPqAlgorithm" ] || [ $3 = "Wz61850Client" ] || [ $3 = "PQMM/lib61850" ] ||
        [ $3 = "WzNetConfig" ] || [ $3 = "WzDaemon" ] || [ $3 == "Hoo" ] || [ $3 == "WzTmp" ]; then

        build_project $3

    else
        if [[ "$PRODUCT" == "A9" ]]; then
            build_A9_project $3
        else
            build_A7_project $3
        fi
    fi

    echo -e "\033[31m $3 build success!\033[0m"

else

    echo -e "\033[31m No Project to build!\033[0m"

fi
